<?php

class Panel extends Controller {

    public function __construct() {
        parent::__construct();
    }

    public function index() {
        Routers::changePage('panel_view', array('title' => 'Painel Administrativo'));
    }

    public function edition_page() {
        Routers::changePage('edition_page_view', array('title' => 'Edição - Página'));
    }

    public function login_admin() {
        if (Session::exists('sessionUser')) {
            return Ajax::response(array('redirect' => ''));
        }
        $msg = "";
        $users = new users();
        $sucesso = true;
        $i = 0;
        $users->post();
        if (empty($users->login)) {
            $msg .= "Informar login! ";
            $i++;
        }
        if (empty($users->password)) {
            $msg .= "Informar a senha! ";
            $i++;
        }
        if ($i > 0) {
            $sucesso = false;
            return Ajax::response(array('message' => $msg, 'status' => 'warning'), array($users));
        }
        $em = new EntityManager();
        $exe = $em->prepare("SELECT U.id FROM users AS U WHERE U.login = :login AND U.password = :password");
        // 527996fe7304d1b83de961ccb7fbcfe9
        $password = md5($users->password);
        $exe->bindParam(":login", $users->login, PDO::PARAM_STR);
        $exe->bindParam(":password", $password, PDO::PARAM_STR);
        if ($exe->execute()) {
            if ($exe->rowCount() > 0) {
                $row = $exe->fetch();
                Session::put('sessionUser', $row['id']);
                return Ajax::response(array('redirect' => 'this'));
            }
        } else {
            $users = new users();
            return Ajax::response(array('message' => 'Login inválido', 'status' => 'warning'), array($users));
        }
    }

    public function logout_admin() {
        session_destroy();
        Helpers::redirect(array('uri' => 'pagina/login'));
    }

    public function contact() {
        // Insira seu código aqui
        // Ex:
        $users = new users();
        //Session::put($user);
        // Helpers::redirect('welcome', true);
        if (!Session::exists('users')) {
            if ($users != Session::get('users')) {
                Session::put('users', $users);
            }
        }
        return "Welcome {$users->login}";
    }

}
